package com.lalameow.loreattr.attribute.attribute.valueattribute;

import com.lalameow.loreattr.attribute.attribute.AbstractValueAttribute;
import com.lalameow.loreattr.attribute.entity.EntityAttribute;
import com.lalameow.loreattr.attribute.util.LoreUtils;
import org.bukkit.entity.LivingEntity;
import org.bukkit.inventory.ItemStack;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Author: SettingDust
 * Date: 2017/6/28.
 */
public class AttributeDamage extends AbstractValueAttribute {
    private final Pattern damageValueRegex = Pattern.compile("[+](\\d+)[ ](" + entityAttribute.getKeyword().toLowerCase() + ")");
    private final Pattern negitiveDamageValue = Pattern.compile("[-](\\d+)[ ](" + entityAttribute.getKeyword().toLowerCase() + ")");
    private final Pattern damageRangeRegex = Pattern.compile("(\\d+)(-)(\\d+)[ ](" + entityAttribute.getKeyword().toLowerCase() + ")");

    public AttributeDamage() {
        super(EntityAttribute.getAttribute("damage"));
    }

    @Override
    public double getAttribute(LivingEntity entity) {
        if (!entity.isValid()) {
            return 0;
        }
        return getValue(LoreUtils.getLore(entity, false, false));
    }

    @Override
    public double getAttribute(ItemStack itemStack) {
        return getValue(LoreUtils.getLore(itemStack));
    }

    public double getValue(List<String> lore) {
        Integer damageMin = 0;
        Integer damageMax = 0;
        Integer damageBonus = 0;
        for (String s : lore) {
            Matcher negValueMatcher = negitiveDamageValue.matcher(s.toLowerCase());
            Matcher rangeMatcher = damageRangeRegex.matcher(s.toLowerCase());
            Matcher valueMatcher = damageValueRegex.matcher(s.toLowerCase());
            if (rangeMatcher.find()) {
                damageMin = Integer.valueOf(rangeMatcher.group(1));
                damageMax = Integer.valueOf(rangeMatcher.group(3));
            }
            if (valueMatcher.find()) {
                damageBonus += Integer.valueOf(valueMatcher.group(1));
                if (negValueMatcher.find()) {
                    damageBonus -= Integer.valueOf(negValueMatcher.group(1));
                }
            }
        }
        if (damageMax < 1) {
            damageMax = 1;
        }
        if (damageMin < 1) {
            damageMin = 1;
        }
        return (int) Math.round(Math.random() * (damageMax - damageMin) + damageMin + damageBonus);
    }

    public boolean useRangeOfDamage(LivingEntity entity) {
        if (!entity.isValid()) {
            return false;
        }
        List<String> lore = LoreUtils.getLore(entity, false, false);
        for (String s : lore) {
            Matcher rangeMatcher = damageRangeRegex.matcher(s.toLowerCase());
            if (rangeMatcher.find()) {
                return true;
            }
        }
        return false;
    }
}
